/**
 * @ByteLoader.as
 * 
 * @author sodaChen mail:asframe@qq.com
 * @version 1.0
 * <br>Copyright (C), 2013 FeiYin.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:Lion3D
 * <br>Date:2013-10-24
 */
package com.asframe.res
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	/**
	 *
	 * @author sodaChen
	 * #Date:2013-10-24
	 */
	public class ByteLoader extends URLLoader
	{
		public static const TIMEOUT:String = 'loaderTimeout';  
		
		/** 服务器响应的超时4s **/
		public var timeout:Number = 4000;
		/** 加载的资源路径 **/
		public var url:String;
		public var request:URLRequest;
		
		private var timeoutTimer:Timer;
		private var isClosed:Boolean;
		
		private var time:int;
		
		public function ByteLoader()
		{
			dataFormat = URLLoaderDataFormat.BINARY;
			request = new URLRequest();
			timeoutTimer = new Timer(timeout);
		}
		private function handleTimeout(event:TimerEvent):void  
		{ 
			killTimer();  
			dispatchEvent(new Event(TIMEOUT));  
		} 
		private function killTimer(event:Event = null):void  
		{  
			removeEventListener(IOErrorEvent.IO_ERROR, killTimer);  
			removeEventListener(SecurityErrorEvent.SECURITY_ERROR, killTimer);  
			removeEventListener(Event.COMPLETE, killTimer);  
			removeEventListener(ProgressEvent.PROGRESS, killTimer); 
			
//			if(timeoutTimer.running)
			timeoutTimer.stop();  
			timeoutTimer.removeEventListener(TimerEvent.TIMER, handleTimeout);  
		} 
		override public function close():void  
		{  
			if(isClosed) return;
			isClosed = true;
			killTimer(); 
			try{
				super.close();
			}catch(e:Error){
				trace(e.getStackTrace());
			};
		}  
		public function start(url:String,loadUrl:String):void
		{
			this.url = url;
			killTimer();
			request.url = loadUrl;
			
//			if(!hasEventListener(ProgressEvent.PROGRESS))
//				addEventListener(ProgressEvent.PROGRESS, killTimer);
			reStart();
		}
		public function reStart():void
		{
			isClosed = false;
			timeoutTimer.delay = timeout;
			addEventListener(IOErrorEvent.IO_ERROR, killTimer);  
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, killTimer);  
			addEventListener(Event.COMPLETE, killTimer);  
			addEventListener(ProgressEvent.PROGRESS, killTimer);
			timeoutTimer.addEventListener(TimerEvent.TIMER, handleTimeout);  
			load(request);
		}
		public function rest():void
		{
			close();
			request.url = null;
		}
	}
}
